<?php
namespace app\admin\controller;
use app\admin\model\Config as ConfigModel;
use app\admin\model\WebSet as WebSetModel;

/**
 * 公众号管理
 */
class Wechat extends Controller
{
    /**
     * 公众号信息
     */
    public function index()
    {
        $wechat = ConfigModel::detail();
        return $this->fetch('index', compact('wechat'));
    }
	
	/**
     * 公众号菜单设置
     */
    public function menu()
    {
		
    }
	
	/**
     * 被关注回复设置
     */
    public function subscribe()
    {
        return $this->updateEvent('subscribe');
    }
	
	/**
     * 无效关键字回复设置
     */
    public function invalid()
    {
        return $this->updateEvent('invalid');
    }
	
	/**
     * 公众号菜单设置
     */
    public function menus()
    {
        return $this->updateEvent('menus');
    }

    /**
     * 更新设置事件
     */
    private function updateEvent($key)
    {
        if (!$this->request->isAjax()) {
            $values = json_encode(WebSetModel::getItem($key));
            return $this->fetch($key, compact('values'));
        }
		//测试判断
		if($this->admin['user']['config_id']==0){
			return $this->renderError('测试用户不可操作');
		}
		$wechat = ConfigModel::detail();
		if(empty($wechat['wechat_appid'])){
			return $this->renderError('还未绑定公众号');
		}
        $model = new WebSetModel;
        if ($model->edit($key,$this->postData('data'))){
            return $this->renderSuccess('更新成功');
        }
        $error = $model->getError() ?: '更新失败';
		return $this->renderError($error);
    }

	/**
     * 一键扫码授权
     */
    public function authorize()
    {
		$auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );	//获取授权码
		$config = ConfigModel::detail();
		if(!empty($auth_code)){
			//获取授权信息
			$result = getAuth($config['app_id'], $config['component_access_token'], $auth_code);
			$auth = $result['authorization_info'];//得到授权信息
			//获取授权应用的帐号基本信息
			$result = getAppInfo($config['app_id'], $config['component_access_token'], $auth['authorizer_appid']);
			$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
			$config->save([
				'wechat_appid' => $auth['authorizer_appid'],//授权方APPid
				'wechat_id' => $app['user_name'],//原始ID
				'wechat_nick' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
				'wechat_logo' => isset($app['head_img'])?$app['head_img']:'',//头像
				'wechat_qrcode' =>$app['qrcode_url'],	//二维码地址
				'wechat_principal' => $app['principal_name'],	//主体名称
				'wechat_access_token' => $auth['authorizer_access_token'],	//令牌
				'wechat_at_expires' => time()+7000,//令牌过期时间
				'wechat_refresh_token' => $auth['authorizer_refresh_token'],//刷新令牌				
			]);
			$this->redirect('wechat/index');
		}
		if(empty($config['app_id']) OR empty($config['component_access_token'])){
			return $this->error('第三方参数配置错误');
		}
		$url = authUrl($config['app_id'],$config['component_access_token'],1);//获取授权页面地址
		$this->redirect($url);
	}
}
